import 'package:app/pages/personnel_module/personnel_model.dart';
import 'package:app/services/address.dart';
import 'package:app/services/dio_manager.dart';
import 'package:flutter/material.dart';

import '../../common/colors.dart';
import 'contact_model.dart';
import 'index_bar.dart';
import 'package:get/get.dart';

class ContactActivePage extends StatefulWidget {
  ContactActivePage({Key? key, required this.positionids}) : super(key: key) {}
  List positionids = [];

  @override
  _ContactActivePageState createState() => _ContactActivePageState();
}

class _ContactActivePageState extends State<ContactActivePage> {
  late List<Data>? _listDatas = []; //列表数据

  late ScrollController _scrollController; //滚动控制器

  final double _cellHeight = 54.0;
  final double _groupHeight = 30.0;
  final Map _groupOffsetMap = {
    INDEX_WORDS[0]: 0.0,
    INDEX_WORDS[0]: 0.0,
  };

  //页面创建渲染的时候走这个方法
  @override
  void initState() {
    super.initState();
    getInitData();
    //创建数据
    _scrollController = ScrollController(); //初始化
  }

  void getInitData() async {
    print("OrganPage==print>>");
    var json = await DioManager()
        .kkRequest(Address.hrEmployee, params: {'': ''}, method: 'get');
    PersonnelModel _model = PersonnelModel.fromJson(json);
    _listDatas = _model.data;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.bgColor,
      appBar: AppBar(
        actions: [
          TextButton(
              onPressed: () {
                List namess = [];
                List nameids = [];
                for (var element in _listDatas!) {
                  if (widget.positionids.contains(element.userId)) {
                    nameids.add(element.userId);
                    namess.add(element.name);
                  }
                }
                print("namess==>>>${namess.length}");
                Get.back(result: {
                  'data': 'refresh',
                  'namess': namess,
                  'positions': nameids
                });
              },
              child: const Text(
                '保存',
                style: TextStyle(color: Colors.blueAccent),
              ))
        ],
        title: const Text(
          '选择参与对象',
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Stack(
        children: [
          Container(
            margin: EdgeInsets.only(top: 15),
            child: ListView.builder(
              itemBuilder: _itemForRow,
              itemCount: _listDatas!.length,
              controller: _scrollController, //控制器
            ),
          ),
          //索引条
          IndexBar(indexBarCallBack: (String str) {
            if (_groupOffsetMap[str] != null) {
              _scrollController.animateTo(_groupOffsetMap[str],
                  duration: const Duration(microseconds: 100),
                  curve: Curves.easeIn);
            }
          })
        ],
      ),
    );
  }

  Widget _itemForRow(BuildContext context, int index) {
    return _FriendCell(
        onPressed: () {
          print("index==>>>$index");
          var userId = _listDatas![index].userId;
          if (widget.positionids.contains(userId)) {
            setState(() {
              widget.positionids.remove(userId);
            });
          } else {
            setState(() {
              widget.positionids.add(userId);
            });
          }
        },
        index: index,
        userid: _listDatas![index].userId,
        currents: widget.positionids,
        imageUrl: _listDatas![index].image128,
        name: _listDatas![index].name);
  }
}

class _FriendCell extends StatelessWidget {
  final int? index; //位置
  final int? userid; //员工id
  final List? currents; //位置
  // final Friends? friends; //员工item
  final String? imageUrl; //图片 URL
  final String? name; //昵称

  final VoidCallback? onPressed;

  const _FriendCell(
      {@required this.onPressed,
      this.index,
      this.userid,
      this.currents,
      this.imageUrl,
      this.name});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        GestureDetector(
            onTap: onPressed,
            child: Container(
              color: Colors.white,
              child: Row(children: [
                Container(
                    margin: const EdgeInsets.all(10),
                    width: 30,
                    height: 30,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6.0),
                        image: DecorationImage(
                          image: getImage(),
                        ))), //图片
                // ignore: avoid_unnecessary_containers
                Container(
                    width: Get.width - 124,
                    child: Column(
                      children: [
                        Container(
                          alignment: Alignment.centerLeft,
                          height: 53.5,
                          child: Text(
                            name!,
                            style: const TextStyle(
                                fontSize: 16, color: Colors.black),
                          ),
                        ),
                        Container(
                          height: 0.5,
                          color: AppColor.lineColor,
                        ), //下划线
                      ],
                    )),
                Container(
                  margin: const EdgeInsets.all(
                    12,
                  ),
                  child: Image.asset(
                    currents!.contains(userid)
                        ? 'images/check_image.png'
                        : 'images/uncheck_image.png',
                    width: 24,
                    height: 24,
                  ),
                ), //昵称
              ]),
            )),
      ],
    );
  }

  ImageProvider getImage() {
    return NetworkImage(Address.homeHost + imageUrl!);
  }
}
